#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/spi.h"

#include "wizchip_conf.h"
#include "bsp_spi.h"
#include "dhcp.h"   // Use dhcp
#include "socket.h" // Use socket
#include "dns.h"    //Use dns
#include "smtp.h"   //Use smtp

#define SOCK_DHCP 0 // DHCP SOCKET
#define SOCK_DNS 1  //DNS SOCKET
#define SOCK_SMTP 2                      // SMTP SOCKET
#define ETHERNET_BUF_MAX_SIZE (1024 * 2) // Send and receive cache size
#define DHCP_RETRY_COUNT 5               // DHCP retry times
#define DNS_RET_FAIL 0
#define DNS_RET_SUCCESS 1
#define DNS_RETRY 5 /* 5 times */

/**
 * @brief   Timer callback processing function, used for dhcp timing processing
 * @param   repeating :Timer structure
 * @return  bool
 */
bool repeating_timer_callback(struct repeating_timer *t);

/**
 * @brief   Initialization of chip network information
 * @param   conf_info :Static configuration information
 * @return  none
 */
void network_init(wiz_NetInfo *conf_info);

/*
   @brief The DNS resolves the domain name.
   @param1 Domain name to be resolved.
   @param2 Domain Resolved IP address.
   @return None.
*/
void do_dns(uint8_t *domain_name, uint8_t *remote_ip);

/* Network information to be configured. */
wiz_NetInfo net_info = {
    .mac = {0x00, 0x44, 0x55, 0x66, 0xed, 0x2e}, // Configured MAC address
    .ip = {192, 168, 1, 10},                     // Configured IP address
    .sn = {255, 255, 255, 0},                    // Configured subnet mask
    .gw = {192, 168, 1, 1},                      // Configured gateway
    .dns = {8, 8, 8, 8},                         // Configured domain address
    .dhcp = NETINFO_DHCP};                       // Configured dhcp model,NETINFO_DHCP:use dhcp; NETINFO_STATIC: use static ip.

static uint8_t ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {
    0,
};
static uint8_t http_tx_ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {
    0,
};
static uint8_t http_rx_ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {
    0,
};
uint8_t Domain_ip[4] = {
    0,
};
uint8_t Domain_name[] = "smtp.126.com";
static uint8_t breakout_flag = 0; // Define the DHCP acquisition flag
uint8_t Mail_Send_OK = 0;
int main()
{
    int i;
    struct repeating_timer timer; // Define the timer structure
    wiz_NetInfo get_info;
    /* MCU init */
    stdio_init_all();     // Initialize the main control peripheral
    wizchip_initialize(); // Initialize the chip interface

    /*dhcp init*/
    DHCP_init(SOCK_DHCP, ethernet_buf);                                   // DHCP initialization
    add_repeating_timer_ms(1000, repeating_timer_callback, NULL, &timer); // Add DHCP 1s Tick Timer handler

    /* mail message init*/
    mailmessage();

    /*dns init*/
    DNS_init(SOCK_DNS, ethernet_buf);
    printf("wiznet chip smtp example.\r\n");
    network_init(&net_info);              // Configuring Network Information
    print_network_information(&get_info); // Read back the configuration information and print it
    do_dns(Domain_name,Domain_ip);
    while (true)
    {
        do_smtp(SOCK_SMTP);
        if (Mail_Send_OK)
        {
            while (true)
                ;
        }
    }
}

void network_init(wiz_NetInfo *conf_info)
{
    int count = 0;
    uint8_t dhcp_retry = 0;

    if (conf_info->dhcp == NETINFO_DHCP)
    {
        while (true)
        {
            switch (DHCP_run()) // Do the DHCP client
            {
            case DHCP_IP_LEASED: // DHCP resolves the domain name successfully
            {
                if (breakout_flag == 0)
                {
                    printf("DHCP success\r\n");
                    getIPfromDHCP((*conf_info).ip);
                    getGWfromDHCP((*conf_info).gw);
                    getSNfromDHCP((*conf_info).sn);
                    getDNSfromDHCP((*conf_info).dns);
                    wizchip_setnetinfo(conf_info); // Configuring Network Information
                    close(SOCK_DHCP);              // After dhcp close the socket, avoid errors in later use
                    breakout_flag = 1;
                }
                break;
            }
            case DHCP_FAILED:
            {
                printf(" DHCP failed \r\n");
                count++;
                if (count <= DHCP_RETRY_COUNT) // If the number of times is less than or equal to the maximum number of times, try again
                {
                    printf("DHCP timeout occurred and retry %d \r\n", count);
                }
                else if (count > DHCP_RETRY_COUNT) // If the number of times is greater than DHCP fails
                {
                    breakout_flag = 1; // if DHCP fail, use the static
                    DHCP_stop();       // Stop processing DHCP protocol
                    conf_info->dhcp = NETINFO_STATIC;
                    wizchip_setnetinfo(conf_info); // Configuring Network Information
                    break;
                }
                break;
            }
            }
            if (breakout_flag)
            {
                printf("config success\r\n");
                break;
            }
        }
    }
    else
    {
        wizchip_setnetinfo(conf_info); // Configuring Network Information
    }
}

void do_dns(uint8_t *domain_name, uint8_t *remote_ip)
{
    uint8_t dns_retry_cnt = 0; // Number of parsings
    uint8_t dns_ok = 0;        // Parse success Peugeot
    wiz_NetInfo read_info = {
        0,
    };
    wizchip_getnetinfo(&read_info);
    while (true)
    {
        if ((dns_ok == 0) && (dns_retry_cnt < DNS_RETRY)) // Determine whether the parsing is successful or whether the parsing exceeds the number of times
        {
            switch (DNS_run(read_info.dns, domain_name, remote_ip)) // Read the DNS_run return value
            {
            case DNS_RET_FAIL: // The DNS domain name is successfully resolved
            {
                dns_retry_cnt++;
                printf("> DNS Failed\r\n");
            }
            break;
            case DNS_RET_SUCCESS: // DNS domain name resolution failed
            {
                dns_ok = 1;
                printf("> Translated %s to %d.%d.%d.%d\r\n", Domain_name, remote_ip[0], remote_ip[1], remote_ip[2], remote_ip[3]);
            }
            break;
            }
        }
        else
        {
            break;
        }
    }
}

bool repeating_timer_callback(struct repeating_timer *t)
{
    DHCP_time_handler(); // DHCP 1s Tick Timer handler
    DNS_time_handler();  // DNS 1s Tick Timer handler
    return true;
}
